package com.timebank.score.service.impl;

import com.timebank.common.core.constant.SecurityConstants;
import com.timebank.common.core.constant.StatusConstant;
import com.timebank.common.core.exception.ServiceException;
import com.timebank.common.core.result.Result;
import com.timebank.common.core.web.pojo.AjaxResult;
import com.timebank.common.security.utils.SecurityUtils;
import com.timebank.score.constant.GoodsStatusConstant;
import com.timebank.score.mapper.GoodsMapper;
import com.timebank.score.mapper.ScoreTradeMapper;
import com.timebank.score.pojo.entity.Goods;
import com.timebank.score.pojo.entity.ScoreTrade;
import com.timebank.score.pojo.vo.GoodsVO;
import com.timebank.score.service.GoodsService;
import com.timebank.system.model.LoginUser;
import com.timebank.system.pojo.SysUser;
import com.timebank.system.service.RemoteUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 商品 实现类
 * @author shiliuyinzhen
 */
@Service
public class GoodsServiceImpl implements GoodsService {

    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private ScoreTradeMapper scoreTradeMapper;

    @Resource
    private RemoteUserService remoteUserService;

    /**
     * 新增商品
     * @param goods
     * @return
     */
    @Override
    public AjaxResult addGoods(Goods goods) {
        goods.setCreateBy(SecurityUtils.getUsername());
        goods.setCreateTime(LocalDateTime.now());
        goods.setStock(goods.getTotal());
        int row = goodsMapper.addGoods(goods);
        return row > 0 ? AjaxResult.success("新增商品成功") : AjaxResult.error("新增商品失败");
    }

    /**
     * 获取商品列表
     * @param goods
     * @return
     */
    @Override
    public List<GoodsVO> getGoodsList(Goods goods) {
        return goodsMapper.getGoods(goods);
    }

    /**
     * 批量删除商品
     * @param goodsIds
     * @return
     */
    @Override
    public AjaxResult batchDeleteGoods(Long[] goodsIds) {
        int row = goodsMapper.batchDeleteGoods(goodsIds);
        return row > 0 ? AjaxResult.success("删除商品成功") : AjaxResult.error("删除商品失败");
    }

    /**
     * 修改商品信息
     * @param goodsId
     * @param goods
     * @return
     */
    @Override
    public AjaxResult updateGoodsById(Long goodsId,Goods goods) {
        int row = goodsMapper.updateGoodsById(goodsId,goods);
        return row > 0 ? AjaxResult.success("修改商品成功") : AjaxResult.error("修改商品失败");
    }

    /**
     * 兑换商品
     * @param goodsId
     * @return
     */
    @Override
    @Transactional
    public AjaxResult exchangeGoods(Long goodsId) {
        //查询用户信息
        Result<LoginUser> result = remoteUserService.getUserInfo(SecurityUtils.getUsername(), SecurityConstants.INNER);
        LoginUser loginUser = result.getData();
        SysUser sysUser = loginUser.getSysUser();
        //查询商品信息
        Goods goods = goodsMapper.getGoodsById(goodsId);
        //如果商品不存在
        if (goods == null){
            throw new ServiceException("商品 id: " + goodsId + "不存在");
        }
        //如果商品已被下架
        if (goods.getStatus().equals(GoodsStatusConstant.DISABLE)){
            throw new ServiceException("商品已下架");
        }
        //如果商品已售完
        if (goods.getStatus().equals(GoodsStatusConstant.SOLD_OUT)
                || goods.getExchange() >= goods.getTotal() ){
            throw new ServiceException("商品已售完");
        }
        //如果积分不够
        if (sysUser.getScore() < goods.getPrice()){
            throw new ServiceException("用户积分不足");
        }
        //创建积分交易
        ScoreTrade scoreTrade = ScoreTrade.builder()
                .goodsId(goodsId)
                .payerId(SecurityUtils.getUserId())
                .payerName(SecurityUtils.getUsername())
                .score(goods.getPrice())
                .createBy("system")
                .createTime(LocalDateTime.now())
                .remark("兑换商品")
                .build();
        int res = scoreTradeMapper.addScoreTrade(scoreTrade);
        if (res <= 0){
            throw new ServiceException("创建积分交易失败");
        }
        //扣除用户积分
        sysUser.setScore(sysUser.getScore() - goods.getPrice());
        Result<Boolean> result1 = remoteUserService.updateUserLoginInfo(sysUser, SecurityConstants.INNER);
        if (result1.getData() == false){
            throw new ServiceException("扣除用户积分失败");
        }
        //如果限量
        if (!(goods.getTotal() == -1 && goods.getStock() == -1)){
            //更新商品库存
            goods.setExchange(goods.getExchange() + 1);
            goods.setStock(goods.getStock() - 1);
            int row = goodsMapper.updateGoodsById(goodsId, goods);
            return row > 0 ? AjaxResult.success("兑换成功") : AjaxResult.error("兑换失败");
        }
        return AjaxResult.success("兑换成功");
    }
}
